package com.oms.config;

import com.oms.common.ResponseCodeConst;
import com.oms.common.ResponseDTO;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author zhanghailong QQ38592077
 * @Description TODO
 * @Date 2020/7/7 14:15
 */
@ControllerAdvice
@ResponseBody
public class GlobalExceptionConfig {
    /**
     *  添加全局异常处理流程，根据需要设置需要处理的异常，此方法以对象参数验证异常处理
     * @param exception
     * @return
     * @throws Exception
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public ResponseDTO<?> methodArgumentNotValidHandler(MethodArgumentNotValidException exception) throws Exception {
        // 将错误信息添加进集合中
        List<String> msg = new ArrayList<>();
        for (FieldError error : exception.getBindingResult().getFieldErrors()) {
            msg.add(error.getDefaultMessage());
        }
        return ResponseDTO.wrapMsg(ResponseCodeConst.ERROR_PARAM, msg.toString());
    }
}
